package com.xzlf.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzlf.domain.NovelChapter;
import com.xzlf.domain.WebSite;
import com.xzlf.service.NovelChapterService;
import com.xzlf.service.WebSiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class ShowController {

    @Autowired
    private WebSiteService webSiteService;

    @Autowired
    private NovelChapterService novelChapterService;

    @GetMapping("/")
    public String showPage(Model model){
        List<WebSite> list = webSiteService.list();
        model.addAttribute("list", list);
        return "index";
    }

    @GetMapping("/{page}/{id}")
    public String getPage(@PathVariable String page, @PathVariable(required = false) String id, Model model){
        model.addAttribute("pid", id);
        return page;
    }

    @PostMapping("/add")
    public String luoqiuAdmin(String pid, String url, int popNum){
        boolean save  = novelChapterService.saveNovel(pid, url, popNum);
        return save ? "addOk" : "addFail";
    }

    @RequestMapping("/findByPage")
    public String findByPage(@RequestParam(defaultValue = "1") int current,
                             @RequestParam(defaultValue = "50") int pageSize,
                             int pid,
                             Model model){
        List<NovelChapter> list = novelChapterService.findByPage(current, pageSize, pid);
        model.addAttribute("list", list);
        return "novelList";
    }

    @GetMapping("/getContent")
    public String getContent(String url, int id, Model model){

        NovelChapter novelChapter = novelChapterService.getById(id);
        if ("next".equals(url)){
            Integer pid = novelChapter.getPid();
            WebSite webSite = webSiteService.getById(pid);
            novelChapter.setContentUrl(webSite.getUrl()+novelChapter.getUri());
            url = novelChapter.getContentUrl();
        }
        String html = novelChapterService.getContent(url);
        model.addAttribute("content", html);
        model.addAttribute("novelChapter", novelChapter);
        return "novelChapter";
    }
}
